<template>
	<view class="page" style="">
		<nav-bar @selectSewlingLine="changeSewingLine" />
		<view class="content">
			<view class="left">
				<view class="l-header">
					<view class="info" style="display: flex;height: 100%;">
						<view class="title-icon"></view>
						<text style="color: #333;font-size: 1.2rem">{{ productionInfo.billNo }}</text>
					</view>
					<view class="info">{{ $t('pages.quality.styleNo') }}：<text>{{ productionInfo.styleNo }}</text></view>
					<view class="info">{{ $t('pages.quality.styleName') }}：<text>{{ productionInfo.styleName }}</text></view>
					<view class="info">{{ $t('pages.quality.customer') }}：<text>{{ productionInfo.customerName }}</text></view>
					<view class="info">{{ $t('pages.quality.pass') }}/{{ $t('pages.quality.order') }}：<text>{{this.productionInfo.orderQualifeidNum || 0 }}/{{ this.productionInfo.orderNum || 0 }}</text></view>
					<view class="info extra-info">
						<u-line-progress :percentage="qualityRate" activeColor="#3EAAF7" :showText="false">
						</u-line-progress>
					</view>
					<view class="flex-center"><view class="changeStyle" @click="changeStyle">{{ $t('pages.quality.exchange') }}</view></view>
				</view>
				<scroll-view scroll-y="true" class="scroll-list">
					<view class="l-listInfo">
						<u-list @scrolltolower="scrolltolower">
							<u-list-item v-for="(item, index) in productionInfo.productionDetailList" :key="index">
								<view :class="item.selectedStyle ? 'active' : 'item'" @click="getStyleData(item,index)">
									<view class="item-info"><text>{{ item.color}}-{{ item.size }}</text></view>
									<view class="item-info"><text>{{ $t('pages.quality.order') }}：</text>{{ item.num }}</view>
									<view class="item-info">
										<!-- <text>已完工：</text>{{ item.iotInspection ? item.iotInspection.qualifiedNum: 0 }} -->
										<text>{{ $t('pages.quality.finished') }}：</text>{{ item.checkQualifiedNum}}
									</view>
								</view>
							</u-list-item>
						</u-list>
					</view>
				</scroll-view>
			</view>
			<view v-if="rightNoData">{{ $t('pages.quality.tipsData') }}</view>
			<view v-else class="right">
				<view class="r-header">
					<view class="h-left">
						<!-- 产量 -->
						<view class="yield">
							<view>{{ $t('pages.quality.todayGoal') }}：<text>{{ productionInfo.goal }}</text></view>
							<view>{{ $t('pages.quality.todayPass') }}：<text>{{ productionInfo.qualifeidNumTotal }}</text></view>
						</view>
						<!-- 图表 -->
						<view v-if="chartShow" class="chart">
							<cycleChart :passRate="passRate" ref="cycleChart" />
						</view>
					</view>
					<view class="h-right">
						<view class="flex-margin">
							<view class="flex-between">
								<view style="text-align: left;">
									<text>{{ currentProductionInfo.color }}-{{ currentProductionInfo.size }}</text>
								</view>
								<view><text
										style="text-align: right;">{{ $t('pages.quality.order') }}/{{ $t('pages.quality.finished') }}：</text>{{ currentProductionInfo.num }}/{{ currentProductionInfo.iotInspection ? currentProductionInfo.iotInspection.qualifiedNum: 0 }}
								</view>
							</view>
							<view class="flex-between">
								<view>{{ $t('pages.quality.today') }}：</view>
								<view class="tableInfo" style="width: 80%;">
									<table style="width: 100%;">
										<th>{{ $t('pages.quality.pass') }}</th>
										<th>{{ $t('pages.quality.rework') }}</th>
										<th>{{ $t('pages.quality.scarp') }}</th>
										<tr style="text-align: center;font-size: 1.2rem;">
											<td style="color: #46C253;">
												{{ currentProductionInfo.iotInspection ? currentProductionInfo.iotInspection.qualifiedNum : '' }}
											</td>
											<td style="color: #FFA631;">
												{{ currentProductionInfo.iotInspection ? currentProductionInfo.iotInspection.unqualifiedNum: ''  }}
											</td>
											<td style="color: #FB602D;">
												{{ currentProductionInfo.iotInspection ? currentProductionInfo.iotInspection.discardedNum: ''  }}
											</td>
										</tr>
									</table>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="r-middle">
					<view class="flex-left-margin">
						<view class="qualified">{{ $t('pages.quality.pass') }}</view>
						<view class="number">
							<u-number-box v-model="currentProductionInfo.qualifiedNum" integer :min="0">
								<view slot="minus" class="minus flex-center">
									<span style="transform: scale(2.5);">—</span>
								</view>
								<u--input v-model="currentProductionInfo.qualifiedNum" slot="input" type="number"
									class="input flex-center" @input="TypeInput($event, 'qualifiedNum')"></u--input>
								<view slot="plus" class="plus flex-center">
									+
								</view>
							</u-number-box>
						</view>
					</view>
					<view class="flex-right">
						<view class="item" v-for="commonNumber in commonInputList" :key="commonNumber"
							@click="currentProductionInfo.qualifiedNum = commonNumber">{{ commonNumber }}</view>
					</view>
				</view>
				<view class="r-bottom">
					<view class="b-left">
						<view class="rework">
							<view class="rework-title">{{ $t('pages.quality.rework') }}</view>
							<view class="number">
								<u-number-box v-model="currentProductionInfo.unqualifiedNum" integer :min="0">
									<view slot="minus" class="minus flex-center">
									<span style="transform: scale(2);">—</span>
									</view>
									<!-- <text slot="input" class="input flex-center">{{value}}</text> -->
									<u--input slot="input" v-model="currentProductionInfo.unqualifiedNum" type="number"
										@input="TypeInput($event, 'unqualifiedNum')" class="input flex-center">
									</u--input>
									<view slot="plus" class="plus flex-center">
										+
									</view>
								</u-number-box>
							</view>
						</view>
						<scroll-view scroll-y="true" class="scroll-Y">
							<view class="falw">
								<!-- <view class="title">{{ $t('pages.quality.defects') }}:</view>
								<view class="falw-list">
									<view class="item" v-for="(item,index) in productionInfo.defectiveSpotList"
										:key="item.id">
										<view>{{ item.defectiveSpot }}</view>
										<view class="number">
											<u-number-box v-model="item.questionNum" integer :min="0">
												<view slot="minus" class="minus flex-center">
													——
												</view>
												<u--input slot="input" v-model="item.questionNum" type="number"
													@input="updateNumber($event, index, 'defectiveSpotList')"
													class="input flex-center"></u--input>
												<view slot="plus" class="plus flex-center">
													+
												</view>
											</u-number-box>
										</view>
									</view>
								</view>-->
								<view class="title">
								<text>{{ $t('pages.quality.defects') }}:</text>
								<view class="plus flex-center" @click.stop="openDefect()">+</view>
								</view>
								<view class="defect-list">
									<view class="detail-content" v-for="item in defectDetail" :key="item.uuid">
										<view class="detail-item">{{ item.defectiveSpot }} * {{ item.questionNum }}</view>
									</view>
								</view>
							</view>
						</scroll-view>
					</view>
					<view class="b-right">
						<view class="scrap">
							<view class="scrap-title">{{ $t('pages.quality.scarp') }}</view>
							<view class="number">
								<u-number-box v-model="currentProductionInfo.discardedNum" integer :min="0">
									<view slot="minus" class="minus flex-center">
										<span style="transform: scale(2);">—</span>
									</view>
									<!-- <text slot="input" class="input flex-center">{{value}}</text> -->
									<u--input slot="input" v-model="currentProductionInfo.discardedNum" type="number"
										@input="TypeInput($event, 'discardedNum')" class="input flex-center"></u--input>
									<view slot="plus" class="plus flex-center">
										+
									</view>
								</u-number-box>
							</view>
						</view>
						<scroll-view scroll-y="true" class="scroll-Y">
							<!-- <view class="problem">
								<view class="title" @click="openProcess">{{ $t('pages.quality.probProcess') }}:</view>
								<view class="falw-list">
									<view class="item" v-for="(item,index) in productionInfo.processList"
										:key="item.id">
										<view>{{ item.processName }}</view>
										<view class="number">
											<u-number-box v-model="item.questionNum" integer :min="0">
												<view slot="minus" class="minus flex-center">
													——
												</view>
												<u--input slot="input" v-model="item.questionNum" type="number"
													@input="updateNumber($event,index,'processList')"
													class="input flex-center"></u--input>
												<view slot="plus" class="plus flex-center">
													+
												</view>
											</u-number-box>
										</view>
									</view>
								</view>
							</view> -->
							
							<!-- 问题工序改 -->
							<view class="problem">
								<view class="title">
								<text>{{ $t('pages.quality.probProcess') }}:</text>
								<view class="plus flex-center" @click.stop="openProcess()">+</view>
								</view>
								<view class="detail-content" v-for="item in problemDetail" :key="item.id">
									<view class="detail-item" v-if="item.questionNum > 0">{{ item.processName }} * {{ item.questionNum }}</view>
								</view>
							</view>
						</scroll-view>
					</view>
				</view>
			</view>
		</view>
		<view class="fixed-button">
			<view class="back">
				<u-button @click="backRouter">{{ $t('common.return') }}</u-button>
			</view>
			<view class="submit">
				<u-button type="primary" :disabled="allowClick" @click="openConfirmModal">{{ $t('common.submit') }}</u-button>
			</view>
		</view>
		<!-- 换款弹出窗 -->
		<styleSelect ref="styleSelect" @selectStyle="getNewStyleInfo" />
		<!-- 问题工序弹出窗 -->
		<problemProcess ref="proAndDef" :process-info="productionInfo.processList" @submitSuccess="setProblemProcess"/>
		<!-- 瑕疵点弹出窗 -->
		<defectSelect 
			ref="defectRef" 
			:defect-info="productionInfo.defectiveTree" 
			:image="productionInfo.image"
			@submitSuccess="setDefect"
		/>
		<!-- 提交提示 -->
		<u-modal :show="confirmShow" :confirmText="$t('common.determine')" :cancelText="$t('common.cancel')"
			:showCancelButton="true" @confirm="confrimHandle" @cancel="confirmShow = false" :content="$t('pages.quality.tips1')"></u-modal>
	</view>
</template>

<script>
	import storage from "@/utils/storage.js"
	import navBar from "@/components/nav/index.vue"
	import styleSelect from "@/components/production/styleSelect.vue"
	import cycleChart from "@/pages/quality/components/cycleChart.vue"
	import problemProcess from "@/pages/quality/components/problemProcess.vue"
	import defectSelect from "@/pages/quality/components/defectSelect.vue"
	import {
		getProduction,
		saveProduction
	} from "@/api/quality.js"
	import { mapState } from 'vuex'

	export default {
		components: {
			navBar,
			cycleChart,
			styleSelect,
			problemProcess,
			defectSelect
		},
		data() {
			return {
				problemDetail: [],
				defectDetail:[],
				confirmShow: false,
				allowClick: false,
				productionId: '',
				sewingId: '',
				currentStyleIndex: 0,
				qualityRate: 0,
				// 生产单信息
				productionInfo: {
					billNo: '',
					styleNo: '',
					styleName: '',
					customerName: '',
				},
				// 工序信息
				processList: [],
				currentProductionInfo: {
					// 下单数量
					orderQuantity: 0,
					// 完成数量
					completedNum: 0,
					// 成衣合格件数
					qualifiedNum: 0,
					// 成衣不合格件数
					unqualifiedNum: 0,
					// 成衣报废件数
					discardedNum: 0,
				},
				chartShow: false,
				passRate: '',
				rightNoData: true,
				allowSave: false,
				scrollTop: 0,
				value: 0,
				commonInputList: [5, 10, 15, 20],
				queryParams: {
					sewingId: this.sewingId,
					productionId: '',
					inspectionId: ''
				},
				indexList: [],
				imgDefectiveData: []
			};
		},
		computed: {
			...mapState(['cacheIdx']),
			// 报废+返工数量
			defectTotal() {
				return Number(this.currentProductionInfo.discardedNum) + Number(this.currentProductionInfo.unqualifiedNum)
			},
			// 质检提交限制 合格+完工+合格＋报废+返工
			// 完工 this.currentProductionInfo.iotInspection.qualifiedNum
			pageLimitTotal() {
				return Number(this.currentProductionInfo.qualifiedNum) + Number(this.currentProductionInfo.iotInspection?.qualifiedNum || 0) +
					Number(this.currentProductionInfo.discardedNum) + Number(this.currentProductionInfo.unqualifiedNum) + Number(this.currentProductionInfo.checkQualifiedNum || 0) +
					Number(this.currentProductionInfo.checkUnqualifiedNum || 0) + Number(this.currentProductionInfo.checkDiscardedNum || 0)
			}
		},
		onLoad(option) {
			this.queryParams.sewingId = option.sewingId
			plus.screen.lockOrientation('landscape-primary') //锁定横屏
		},
		watch: {
			cacheIdx: function(nVal, oVal) {
				console.log('CACHE_IDX: ', nVal);
				this.getProductionInfo()
			}
		},
		mounted() {
			this.getProductionInfo()
		},
		methods: {
			initInfo() {
				this.$refs.defectRef.initData()
				this.clearQuestionNum()
				this.currentProductionInfo.qualifiedNum = 0
				this.currentProductionInfo.unqualifiedNum = 0
				this.currentProductionInfo.discardedNum = 0
			},
			openProcess() {
				this.$refs.proAndDef.open()
			},
			openDefect() {
				this.$refs.defectRef.open()
			},
			setProblemProcess(e) {
				if (e && e.length > 0) {
					this.problemDetail = e.filter(item => item.questionNum > 0)
				}
			},
			setDefect(e = [], imgDefectiveData) {
				if (e) {
					this.defectDetail = e.filter(item => item.questionNum > 0)
				}
				if (imgDefectiveData) {
					this.imgDefectiveData = imgDefectiveData
				}
			},
			// 每次切换sku清空问题工序和瑕疵点
			clearQuestionNum() {
				if(this.productionInfo.processList && this.productionInfo.processList.length > 0) {
					this.productionInfo.processList.map(item => item.questionNum = null)
					this.problemDetail = []
				}
				if(this.productionInfo.defectiveSpotList && this.productionInfo.defectiveSpotList.length > 0) {
					this.defectDetail = []
					this.productionInfo.defectiveSpotList.map(item => item.questionNum = null)
				}
			},
			confrimHandle() {
				this.saveProductionInfo()
				this.confirmShow = false
			},
			openConfirmModal() {
				if(!this.currentProductionInfo.qualifiedNum && !this.currentProductionInfo.discardedNum && !this.currentProductionInfo.unqualifiedNum){
					plus.nativeUI.toast(`<p style=\"font-size: 28px\">${this.$t('pages.quality.tips0')}</p>`,{
						type: "richtext",
						duration: "long",
						verticalAlign: "middle"
					}
					);
					return
				}
				if (( Number(this.currentProductionInfo.qualifiedNum) + Number(this.currentProductionInfo.iotInspection?.qualifiedNum || 0) ) > Number(this.currentProductionInfo.num)) {
					this.confirmShow = true
				}else {
					this.saveProductionInfo()
				}
			},
			TypeInput(e, type) {
				// 只能输入数字的验证;
				const inputType = /[^\d]/g //想限制什么类型在这里换换正则就可以了
				this.$nextTick(function() {
					if (type === 'qualifiedNum') {
						this.currentProductionInfo.qualifiedNum = e.replace(inputType, '');
					} else if (type === 'unqualifiedNum') {
						this.currentProductionInfo.unqualifiedNum = e.replace(inputType, '');
					} else {
						this.currentProductionInfo.discardedNum = e.replace(inputType, '');
					}

				})
			},
			updateNumber(e, index, type) {
				const inputType = /[^\d]/g //想限制什么类型在这里换换正则就可以了
				if (type === 'processList') {
					this.productionInfo.processList[index].questionNum = e.replace(inputType, '');
				} else {
					this.productionInfo.defectiveSpotList[index].questionNum = e.replace(inputType, '');
				}
			},
			// 获取产量登记信息
			getProductionInfo() {
				getProduction(this.queryParams).then(res => {
					if (res.code !== 0) {
						plus.nativeUI.toast(`<p style=\"font-size: 28px\">${res.msg}</p>`,{
							type: "richtext",
							duration: "long",
							verticalAlign: "middle"
						}
						);
						return
					}
					this.productionInfo = res.data
					console.log(res.data, ' res.data');
					if (res.data.productionDetailList && res.data.productionDetailList.length > 0) {
						this.rightNoData = false
						this.calculationPassRate()
						res.data.productionDetailList.map(item => {
							item.selectedStyle = false
						})
						// res.data.productionDetailList[0].selectedStyle = true
						res.data.productionDetailList[this.currentStyleIndex].selectedStyle = true
						this.getStyleData(this.productionInfo.productionDetailList[this.currentStyleIndex], this.currentStyleIndex)
						// this.currentProductionInfo = res.data.productionDetailList[0]
						// this.productionId = this.currentProductionInfo.orderId
					} else {
						this.rightNoData = true
						this.qualityRate = 0
					}
				})
			},
			// 计算合格率
			calculationPassRate() {
				if (this.productionInfo.orderQualifeidNum && this.productionInfo.orderNum) {
					// 合格/下单
					this.qualityRate = (this.productionInfo.orderQualifeidNum / this.productionInfo.orderNum)
					this.qualityRate = Number(this.qualityRate.toFixed(2)) * 100
				}else {
					this.qualityRate = 0
				}
				if (this.productionInfo.goal && this.productionInfo.qualifeidNumTotal) {
					this.passRate = ((this.productionInfo.qualifeidNumTotal / this.productionInfo.goal) * 100).toFixed(0)
					this.chartShow = true
					setTimeout(() => {
						this.$refs.cycleChart.getServerData()
					}, 200)
				} else {
					this.chartShow = false
				}
			},
			//保存
			saveProductionInfo() {
				// 校验数量
				// if (Number(this.pageLimitTotal) > Number(this.currentProductionInfo.num)) {
				// 	return uni.$u.toast("该生产单sku完成数量超出下单数量")
				// }
				// 校验瑕疵点和问题工序数量不能大于返工和报废量
				if (this.productionInfo.processList && this.productionInfo.processList.length > 0) {
					let flag = this.productionInfo.processList.some(item => Number(item.questionNum || '0') > this
						.defectTotal)
					if (flag){
						plus.nativeUI.toast(`<p style=\"font-size: 28px\">${this.$t('pages.quality.tips3')}</p>`,{
							type: "richtext",
							duration: "long",
							verticalAlign: "middle"
						}
						);
						return
					} 
				}
				if (
					this.defectDetail && 
					this.defectDetail.length > 0
				) {
					let flag = this.defectDetail.some(item => Number(item.questionNum || '0') > this
						.defectTotal)
					if (flag) {
						plus.nativeUI.toast(`<p style=\"font-size: 28px\">${this.$t('pages.quality.tips2')}</p>`,{
							type: "richtext",
							duration: "long",
							verticalAlign: "middle"
						}
						);
						return
					}
				}
				
				let params = {
					productionId: this.productionId,
					sewingId: this.queryParams.sewingId,
					billNo: this.productionInfo.billNo,
					styleNo: this.productionInfo.styleNo,
					styleName: this.productionInfo.styleName,
					customerName: this.productionInfo.customerName,
					processesList: this.productionInfo.processList,
					defectiveSpotList: this.productionInfo.image ? this.imgDefectiveData : this.defectDetail
					// defectiveSpotList: this.productionInfo.defectiveSpotList
				}
				params = {
					...this.currentProductionInfo,
					...params
				}

				console.log(params, '==========');

				// this.allowClick = true
				// saveProduction(params, { custom: { loading: false } })
				// this.initInfo()
				// uni.$u.toast(this.$t('common.success'))
				// setTimeout(() => {
				// 	this.getProductionInfo()
				// 	this.allowClick = false
				// }, 500)

				uni.request({
					url: "http://www.baidu.com",
					success: async () => {
						console.log('有网提交');
						this.allowClick = true
						await saveProduction(params, { custom: { loading: false } })
						this.initInfo()
						this.getProductionInfo()
						this.allowClick = false
						uni.$u.toast(this.$t('common.success'))
					},
					fail: () => {
						console.log("网络状态异常, 缓存提交");
						this.isConnected = false

						// 缓存请求数据
						const offlineCaching = uni.getStorageSync('offlineCaching') || {}
						const currentSewingId = storage.get('currentSewingId')
						offlineCaching[currentSewingId] = offlineCaching[currentSewingId] || []
						offlineCaching[currentSewingId]?.push(params)
						uni.setStorageSync("offlineCaching", offlineCaching)
						uni.$u.toast(this.$t('tip.cacheSuccess'))
						this.initInfo()
					}
				})
			},
			// 获取生产单数据
			getStyleData(item, index) {
				this.productionInfo.productionDetailList.map((item, i) => {
					if (i === index) {
						item['selectedStyle'] = true
					} else {
						item['selectedStyle'] = false
					}
				})
				this.currentStyleIndex = index
				this.currentProductionInfo = this.productionInfo.productionDetailList[index]
				this.productionId = this.currentProductionInfo.orderId
				this.clearQuestionNum()
			},
			// 页面滑动到底部
			scrolltolower() {
				console.log('已经到底部了')
				// this.getList()
			},
			backRouter() {
				uni.navigateBack({
					delta: 1
				})
			},
			// 换款打开款式选择弹窗
			changeStyle() {
				// this.$refs.styleSelect.queryParams.sewingId = this.queryParams.sewingId
				this.$nextTick(() => {
					this.$refs.styleSelect.openDialog(this.queryParams.sewingId, '/iot-mobile-api/inspection/changeProductionPage')
				})
			},
			getNewStyleInfo(e) {
				this.queryParams.productionId = e.id
				this.getProductionInfo()
			},
			// 切换缝制线
			changeSewingLine(e) {
				this.queryParams.sewingId = e
				this.queryParams.productionId = ''
				this.getProductionInfo()
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'index.scss';
</style>
